package at.ac.tuwien.dse.health.security.authentication;

import at.ac.tuwien.dse.health.entity.Account;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.StringFormattedMessage;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;

/**
 * Processes an authentication request by performing a database lookup checking whether the credentials are correct.
 *
 * @author Bernhard Nickel
 * @author Gregor Schauer
 * @author Dominik Strasser
 */
public class DatabaseAuthenticationManager implements AuthenticationManager {
	private static final Logger LOGGER = LogManager.getLogger(DatabaseAuthenticationManager.class);
	@PersistenceContext
	EntityManager entityManager;

	@Override
	@Transactional
	public Account authenticate(String username, String password) {
		try {
			return (Account) entityManager.createNamedQuery(Account.BY_USERNAME_PASSWORD)
					.setParameter("username", username).setParameter("password", password).getSingleResult();
		} catch (NoResultException e) {
			// Invalid credentials
		} catch (PersistenceException e) {
			LOGGER.debug(new StringFormattedMessage("Login request failed for user '%s': ", username), e);
		}
		return null;
	}
}
